# -*- coding: utf-8 -*-
# @time:2025/4/4:21:33
# @IDE:PyCharm

import json
import os
from tkinter import messagebox


def load_config(app, file_path=None):
    if file_path is None:
        file_path = app.config_file
    if not os.path.exists(file_path):
        if file_path == app.config_file:
            app.update_status("未找到默认配置文件。使用默认设置。")
        else:
            messagebox.showwarning("加载配置", f"选择的配置文件不存在:\n{file_path}", parent=app.root)
            app.update_status("警告: 配置文件未找到。")
        return
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            config = json.load(f)
        app.input_dir.set(config.get("input_dir", ""))
        app.output_dir.set(config.get("output_dir", ""))
        app.book_name.set(config.get("book_name", "processed_book"))
        saved_format = config.get("book_format", "采样点对齐拼版")
        if saved_format in app.book_format_options:
            app.book_format.set(saved_format)
        else:
            app.book_format.set("采样点对齐拼版")
        app.ground_height.set(config.get("ground_height", 0))
        app.dpi.set(config.get("dpi", 300))
        app.margin_white.set(config.get("margin_white", 5))
        app.save_format.set(config.get("save_format", "jpg"))
        app.preview_image_index.set(config.get("preview_image_index", 0))
        app.show_processed_image.set(config.get("show_processed_image", True))
        point_positions = config.get("point_positions", [0.15, 0.85, 0.15, 0.85])
        for i, pos in enumerate(point_positions):
            try:
                val = float(pos)
                if 0.0 <= val <= 1.0 and i < len(app.point_positions):
                    app.point_positions[i].set(val)
            except (ValueError, TypeError):
                pass
        app.update_status(f"配置已从 {os.path.basename(file_path)} 加载。")
        app.load_image_list()
        app.preview()
        app.on_format_change()
    except json.JSONDecodeError as e:
        messagebox.showerror("加载配置错误", f"配置文件格式错误:\n{file_path}\n错误: {e}", parent=app.root)
        app.update_status("错误: 配置文件格式无效。")
    except Exception as e:
        messagebox.showerror("加载配置错误", f"加载配置文件时发生未知错误:\n{file_path}\n错误: {e}", parent=app.root)
        app.update_status("错误: 加载配置失败。")


def save_config(app, file_path=None):
    if file_path is None:
        file_path = app.config_file
    config = {
        "input_dir": app.input_dir.get(),
        "output_dir": app.output_dir.get(),
        "book_name": app.book_name.get(),
        "book_format": app.book_format.get(),
        "ground_height": app.ground_height.get(),
        "dpi": app.dpi.get(),
        "margin_white": app.margin_white.get(),
        "save_format": app.save_format.get(),
        "preview_image_index": app.preview_image_index.get(),
        "point_positions": [var.get() for var in app.point_positions],
        "show_processed_image": app.show_processed_image.get(),
    }
    try:
        with open(file_path, "w", encoding="utf-8") as f:
            json.dump(config, f, ensure_ascii=False, indent=4)
        app.update_status(f"配置已保存到 {os.path.basename(file_path)}")
        messagebox.showinfo("保存配置", f"配置已成功保存到:\n{file_path}", parent=app.root)
    except Exception as e:
        messagebox.showerror("保存配置错误", f"无法保存配置文件:\n{e}", parent=app.root)
        app.update_status("错误: 保存配置失败。")